<script setup>
import {ref,onMounted,onUnmounted} from 'vue'
import axios from 'axios'
import { SimpleWebSocket } from '../utils/websocket'

const eventName=ref('')
const dataItems=ref([])
const ws=new SimpleWebSocket('ws://localhost:8080/data-ws')
const handleWebSocketMessage=(data)=>{
    console.log('Received data:',data)
    if(data.includes("定时")){
        addDataItem('scheduled',data)
    }else if(data.includes("事件")){
        addDataItem('event',data)
    }else{
        addDataItem('unknown',data) 
    }
}

const addDataItem=(type,content)=>{
    dataItems.value.push({type,content})
}
const triggerData=async()=>{
    try{
        await axios.post('/api/trigger',{
            'event':eventName.value
        })
        eventName.value=''
    }catch(error){
        addDataItem('error','触发数据失败:'+error.message)
    }
}

onMounted(()=>{
    ws.setOnMessagge(handleWebSocketMessage)
    ws.connect()
})
onUnmounted(()=>{
    ws.disconnect()
})
</script>
<template>
    <div class="monitor-container">
        <el-card class="box-card">
            <div class="card-header"><span>实时数据监控</span></div>
            <el-scrollbar height="300px">
                <div 
                v-for="(item,index) in dataItems"
                :key="index"
                class="data-item"
                :class="item.type"
                >
                    <strong>{{ item.type }}</strong>{{ item.content }}
                </div>
            </el-scrollbar>
        </el-card>
        <el-card class="box-card">
            <div class="card-header"><span>触发数据</span></div>
            <div class="trigger-container">
                <el-input
                v-model="eventName"
                placeholder="输入事件名称"
                @keyup.enter="triggerData"
                />
                <el-button
                type="primary"
                @click="triggerData"
                >触发数据</el-button>
            </div>
        </el-card>
    </div>

</template>
<style scoped>
.monitor-container{
    margin: 20px auto;
    max-width: 800px;
}
.box-card{
    margin-bottom: 20px;
}
.card-header{
    font-weight: bold;
}
.trigger-container{
    display: flex;
    gap: 10px;
}
.data-item{
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 8px;
    background-color: #f5f5f5;
}
.data-item.scheduled{
    border-left: 4px solid #409EFF;
}
.data-iteml.event{
    border-left: 4px solid #67C23A;
}
</style>